package com.shao.im.webSocket.handler;

import com.shao.im.entity.Message;
import com.shao.im.webSocket.base.BaseChannelInHandler;
import com.shao.im.webSocket.utils.ChannelManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
@ChannelHandler.Sharable
public class ChatChannelInHandler extends BaseChannelInHandler {
    @Override
    protected int action() {
        return 101;
    }

    @Override
    protected void handler(ChannelHandlerContext ctx, Message message) {
        Integer to = message.getTo();
        Channel channel = ChannelManager.get(to);
        Optional.ofNullable(channel)
                .ifPresent(c -> {
                    // 将消息直接转发给好友
                    c.writeAndFlush(message);
                });
    }
}
